package i2.application.checklist.entities;

import static javax.persistence.GenerationType.AUTO;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name = "categorie")
@NamedQuery(name = "Categorie.getAllCategoriesWithQuestions",
		query = "SELECT DISTINCT c FROM Categorie c JOIN FETCH c.questions")
public class Categorie implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy = AUTO)
	@Column(name = "id", unique = true, nullable = false)
	private int id;
	
	@Column(name = "nom", nullable = false, length = 45)
	@NotNull
	@NotEmpty
	private String nom;

	@OneToMany(mappedBy = "categorie", fetch = FetchType.LAZY)
	private List<Question> questions;
	
	@OneToMany(mappedBy = "categorie", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
	private List<LivrableChamp> livrableChamps = new ArrayList<LivrableChamp>();
	
	public Categorie() {
	}
	
	public Categorie(int id){
		this.id = id;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getNom() {
		return nom;
	}

	public void setNom(String nom) {
		this.nom = nom;
	}
	
	public List<Question> getQuestions() {
		return questions;
	}

	public void setQuestions(List<Question> questions) {
		this.questions = questions;
	}

	public List<LivrableChamp> getLivrableChamps() {
		return livrableChamps;
	}

	public void setLivrableChamps(List<LivrableChamp> livrableChamps) {
		this.livrableChamps = livrableChamps;
	}
	
	public void addChamp(LivrableChamp livrableChamp) {
		livrableChamps.add(livrableChamp);
	}

	public void deleteChamp(int indexChamp) {
		livrableChamps.remove(indexChamp);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}

    @Override
	public boolean equals(Object obj) {
		if (this == obj){
			return true;
		}
		if (obj == null){
			return false;
		}
		if (getClass() != obj.getClass()){
			return false;
		}
		Categorie other = (Categorie) obj;
		if (id != other.id){
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return "Categorie [id=" + id + ", nom=" + nom + 
		", livrableChamps=" + (livrableChamps==null?"null":livrableChamps) + "]";
	}

}
